<template>
  <view class="Enroll">
    <cu-form ref="profileForm">

      <view class="form-group">
        <cu-input name="STUDENTNAME" title="真实姓名" required placeholder="请输入真实姓名"/>
      </view>

      <view class="form-group">
        <cu-input type="number" name="STUDENTNO" title="学号" required placeholder="请输入学号"/>
      </view>

      <view class="form-group">
        <cu-input type="idcard" name="SFZNO" title="身份证号" required placeholder="请输入身份证号"/>
      </view>

      <view class="form-group">
        <cu-input maxlength="11" name="PHONENO" title="联系电话" required placeholder="请输入联系电话"/>
      </view>

      <view class="form-group">
        <cu-input name="ADDR" title="现住址" required placeholder="请输入现住址"/>
      </view>

      <view class="form-group">
        <cu-radio name="SEX" title="性别" :options="sexOpt"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input name="LXR" title="联系人" required placeholder="请输入联系人姓名"/>
      </view>

      <view class="form-group">
        <cu-input type="number" name="LXR_PHONENO" title="联系人电话" required placeholder="请输入联系人电话"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-picker name="ZZMM" title="政治面貌" required :options="ZZMMOpts"/>
      </view>

      <view class="form-group">
        <cu-picker name="WHCD" title="文化程度" required :options="WHCDOpts"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-input name="YDW" title="原单位" required placeholder="请输入原单位"/>
      </view>

      <view class="form-group">
        <cu-input name="YZW" title="原职位" required placeholder="请输入原职位"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <cu-uploader name="PICID" required title="个人照片上传"/>
      </view>

      <view class="margin"></view>

      <view class="form-group">
        <view class="bg-white padding">
          <view class="title">已选专业班： </view>
          <view class="text-sm text-black margin-top-sm">{{ selectedClassesNames }}</view>
        </view>
      </view>

      <view class="form-group">
        <view class="padding text-sm flex justify-between">
          <text class="text-blue" @tap="toCommitLetter">查看《健康安全承诺书》并签名</text>
          <text class="text-red" v-if="!hasRead">尚未完成</text>
          <text v-else class="text-green">已完成</text>
        </view>
      </view>

      <view class="form-group bg-white padding" v-if="ZKCNS && hasRead">
        <view class="grid grid-square col-4">
          <view class="bg-img" @tap="previewImage(ZKCNS)">
            <image :src="ZKCNS" mode="aspectFill"></image>
          </view>
        </view>

        <button class="cu-btn bg-green margin-top" v-if="!ZKCNSID" @tap="uploadZKCNS">
          点击上传<text class="cuIcon-upload"></text>
        </button>

        <view class="text-sm text-green margin-top-sm" v-else>
          已上传<text class="cuIcon-check"></text>
        </view>
      </view>

      <view class="padding">
        <button @tap="onSubmitEnroll" class="cu-btn bg-blue block lg round shadow margin-top-lg">提交报名</button>
      </view>
    </cu-form>
  </view>
</template>

<script lang="ts" setup>
import {computed, onBeforeUnmount, reactive, ref} from "vue";
import {getUserData} from "../../api/manage";
import {useStore} from "vuex";
import CuInput from '../../components/cu-input/index.vue'
import CuRadio from '../../components/cu-radio/index.vue'
import CuPicker from '../../components/cu-picker/index.vue'
import CuForm from '../../components/cu-form/index.vue'
import CuUploader from '../../components/cu-uploader/index.vue'
import {useProfileArgs} from "../profile/useProfileArgs";
import {onLoad, onUnload} from "@dcloudio/uni-app";
import {FetchKXClassListDAT} from "../../types/responseTypes";
import {usePreview} from "../../utils/usePreview";
import {updateEnrollForm} from "../../api/enroll";
import {uploadImg} from "../../api/pictures";

const profileForm = ref<any>(null)
const ZKCNSID = ref('')
const {CUSER_ID, USERNO,USERNAME} = useStore().state.user.userInfo
const {previewImage} = usePreview()
const {ZZMMOpts, WHCDOpts, sexOpt} = useProfileArgs([
  {
    CSNAME: '政治面貌',
    key: 'ZZMMOpts'
  },
  {
    CSNAME: '文化程度',
    key: 'WHCDOpts'
  },
  {
    CSNAME: '性别',
    key: 'sexOpt'
  }
]).opts
let selectedClasses = reactive<FetchKXClassListDAT[]>([])
const hasRead = ref<boolean>(false)
const ZKCNS = ref('')

const selectedClassesNames = computed(() => selectedClasses.map(item => item.CLASSNAME).join('、'))

onLoad((options) => {
  selectedClasses.push(...JSON.parse(decodeURIComponent(options.classes as string)))
  getUserData(CUSER_ID).then(res => {
    if (res.ERROR[0].errcode == '0'){
      if (res.DAT.length > 0){
        profileForm.value.setFields(['STUDENTNAME','STUDENTNO','PICID','SFZNO','SEX','ADDR','PHONENO','LXR','LXR_PHONENO','ZZMM','WHCD','YDW','YZW'].map(name => ({
          value: res.DAT[0][name],
          name
        })))
      }
    }else {
      uni.showToast({
        title: res.ERROR[0].error,
        icon: 'none',
        mask: true
      })
    }
  }).catch(err => {
    uni.showToast({
      title: '获取用户信息失败',
      icon: 'none',
      mask: true
    })
  })
})

function toCommitLetter() {
  uni.navigateTo({
    url: '/pages/commitment/index',
    success: () => {
      uni.$on('finishSign',(res) => {
        hasRead.value = true
        ZKCNS.value = res
      })
    }
  })
}

onBeforeUnmount(() => {
  uni.$off('finishSign')
})

function onSubmitEnroll() {
  (profileForm.value.submit() as Promise<any>).then(async values => {
    if (!hasRead.value){
      uni.showToast({
        title: '请先阅读并签署健康安全承诺书',
        icon: 'none',
        mask: true
      })
      return
    }

    if (!ZKCNSID.value){
      uni.showToast({
        title: '请先上传健康安全承诺书',
        icon: 'none',
        mask: true
      })
      return
    }
   

    try {
      const {STUDENTNAME,STUDENTNO,PICID,SFZNO,SEX,ADDR,PHONENO,LXR,LXR_PHONENO,ZZMM,WHCD,YDW,YZW} = values
      const res = await updateEnrollForm({
        STUDENTNAME,STUDENTNO,PICID,SFZNO,SEX,ADDR,PHONENO,LXR,LXR_PHONENO,ZZMM,WHCD,YDW,YZW,
        STATE: 1,
        OPERATOR_ID: CUSER_ID,
        ZKCNSID: ZKCNSID.value,
        CUSER_ID,
        USERNAME,
        USERNO,
        CLASS_IDS: selectedClasses.map(item => item.CLASS_ID).join(';'),
        ENROLL_ID: '0'
      })

      if (res.ERROR[0].errcode == '0'){
        uni.showToast({
          title: '提交成功',
          icon: "success",
          mask: true
        })

        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/index'
          })
        },500)
      }else {
        uni.showToast({
          title: res.ERROR[0].error,
          icon: "none",
          mask: true
        })
      }
    }catch (err){
      uni.showToast({
        title: '提交失败',
        icon: 'none',
        mask: true
      })
    }


  }).catch(err => {
    uni.showToast({
      title: '请完善相关资料后再提交',
      icon: 'none',
      mask: true
    })
  })
}

async function uploadZKCNS(){
  try {
    const res = await uploadImg({
      FLAG: 'CNS',
      CUSER_ID,
      filePath: ZKCNS.value
    })

    ZKCNSID.value = res.DATA.filename
  }catch (err){
    uni.showToast({
      title: '上传失败',
      icon: 'error',
      mask: true
    })
  }

}

onUnload(() => {
  uni.$off('finishSign')
})
</script>

<style scoped lang="scss">
.Enroll{
  box-sizing: border-box;
  padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
  padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/

  .form-group+.form-group{
    border-top: 1upx solid #eee;
  }
}
</style>
